const { app, BrowserWindow, ipcMain } = require('electron')
const tcp = require('net')
const udp = require('dgram')

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

function createWindow () {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        minWidth: 500,
        minHeight: 603,
        webPreferences: {
            nodeIntegration: true
        }
    })
    let paggg = "lauwen";
    win.loadFile('index.html')
    win.webContents.openDevTools()

    // 发送消息到渲染进程（页面）
    win.webContents.on('did-finish-load', () => {
        win.webContents.send('main-to-page', "dsadasdada")
    })
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})

// 异步接收传递方式
ipcMain.on('two-way', (event, arg) => {
    console.log(arg)
    event.reply("two-way-reply", "asyn reply1")
})

// 同步接受传递方式
ipcMain.on('two-way-syn', (event, arg) => {
    console.log(arg)
    event.returnValue = "syn reply1"
})

// 异步接收传递方式
let client
let clients = []
let connect_info
ipcMain.on('connection', (event, arg) => {
    connect_info = JSON.parse(arg);
    console.log(connect_info)
    if (connect_info.type == "tcp") {
        client = new tcp.Socket();
        client.connect(connect_info.port, connect_info.host, () => {
            console.log("Connect to:"+connect_info.host+":"+connect_info.port)
            client.write("first")
            event.reply("connection-reply", 201)
        })
        client.on('data', function (data) {
            event.reply("connection-reply", data)
        })
        client.on("error", (err) => {
            console.log(err)
            event.reply("connection-reply", 401)
        })

        client.on("close", (data) => {
            console.log('Connection closed')
            event.reply("connection-reply", 301)
        })
    }else if (connect_info.type == "tcps") {
        client = new tcp.createServer((socket) =>{
            clients.push(socket)
            socket.on('data', function (data) {
                console.log(data)
                socket.write("hello")
                event.reply("connection-reply", data)
            })
            socket.on("error", (err) => {
                console.log(err)
                event.reply("connection-reply", 401)
            })

            socket.on("end", () => {
                console.log('Connection closed')
                event.reply("connection-reply", "Connection closed")
            })
        }).listen(connect_info.port, connect_info.host)
        client.on("connection", (info) => {
            console.log("Connected:"+info.remoteAddress+":"+info.remotePort)
            event.reply("connection-reply", "Connected:"+info.remoteAddress+":"+info.remotePort)
        })
        client.on('listening', function () {
            event.reply("connection-reply", 201)
        })
        client.on("close", () => {
            // console.log("Closed:"+info.remoteAddress+":"+info.remotePort)
            event.reply("connection-reply", 301)
        })
    }else if (connect_info.type == "udp") {
        client = new udp.createSocket('udp4')
        event.reply("connection-reply", 201)
        client.on('close',function(){
            console.log('udp client closed.')
            event.reply("connection-reply", 301)
        })

        client.on('error', function () {
            console.log('some error on udp client.')
            event.reply("connection-reply", 401)
        })

        client.on('message', function (msg,rinfo) {
            console.log(`receive message from ${rinfo.address}:${rinfo.port}：${msg}`);
            event.reply("connection-reply", msg)
        })
    }else if (connect_info.type == "udps") {
        client = new udp.createSocket('udp4')
        client.bind(connect_info.port, connect_info.host)
        client.on('listening',function(){
            console.log('udp server open.')
            event.reply("connection-reply", 201)
        })

        client.on('message', function (msg, info) {
            msg = msg.toString();
            client.send("Server"+msg, 0, msg.length+6, info.port, info.address); //将接收到的消息返回给客户端
            console.log(`udp server received data: ${msg} from ${info.address}:${info.port}`)
            event.reply("connection-reply", `udp server received data: ${msg} from ${info.address}:${info.port}`)
        })
        client.on('error', function (err) {
            console.log('some error on udp server.')
            client.close();
            event.reply("connection-reply", 401)
        })
        client.on('close', function (err) {
            console.log('close udp server.')
            event.reply("connection-reply", 301)
        })

    }


})

ipcMain.on('close', () => {
    console.log("close")
    if (connect_info.type == "tcp"){
        client.destroy()
        return
    }else if (connect_info.type == "tcps"){
        for (let i in clients) {
            clients[i].destroy();
        }
    }
    client.close()
})
ipcMain.on('send', (event, arg) => {
    console.log(arg)
    if (connect_info.type == "tcp"){
        client.write(arg)
        return
    }else if (connect_info.type == "tcps"){
        for (let i in clients) {
            clients[i].write(arg)
        }
    }else if (connect_info.type == "udp"){
        client.send(arg, 0, arg.length, connect_info.port, connect_info.host)
    }
})




